package cn.fl.custpay.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.customer.vo.CstBankVO;
import cn.fl.custpay.service.ICmmBindingCartService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import fl.customer.facade.customer.condition.CstBankQueryCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 *
 *@Description 绑卡管理 控制层
 *@Author shijb
 *@Date 2018/7/6 10:54
 *@return
 **/
@Controller
@RequestMapping("/custpay/cmmBindingCart")
public class CmmBindingCartController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CmmBindingCartController.class);

    @Autowired
    private ICmmBindingCartService cmmCmmBindingCartService;

    @RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("custpay/cmmBindingCart/cmmBindingCartListPage");

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 初始化
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initCmmBindingCartList.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        Long staTime = System.currentTimeMillis();
        String accNm = request.getParameter("accNm");
        String cardTel = request.getParameter("cardTel");
        String accNo = request.getParameter("accNo");
        String certNo = request.getParameter("certNo");

        BaseLogUtils.info(logger, "initList", "初始化绑卡管理了列表. 参数传入:"+ JSONObject.toJSONString(accNm) , CurrentThreadContext.getCurrentUserName());

        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        CstBankQueryCondition condition = new CstBankQueryCondition();
        if (StringUtils.isNotEmpty(accNm)) {
            condition.setAccNm(accNm);
        }
        if (StringUtils.isNotEmpty(cardTel)) {
            condition.setCardTel(cardTel);
        }
        if (StringUtils.isNotEmpty(accNo)) {
            condition.setAccNo(accNo);
        }
        if (StringUtils.isNotEmpty(certNo)) {
            condition.setCertNo(certNo);
        }
        page.setCondition(condition);

        //TODO SOMETHING
        Pager pager = this.cmmCmmBindingCartService.searchListPage(page);

        List<CstBankVO> list = (List<CstBankVO>)pager.getResultList();
        ListPageVO<CstBankVO> listPage = new ListPageVO<CstBankVO>(list, pager.getTotalCount());
        Long endTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "initList", "查询数据完成.耗时:" + (endTime - staTime) + "毫秒");
        return listPage;
    }

    /**
     *
     * @Description 获取客户开户行单条信息
     * @Author shijb
     * @Date 2018/7/10 10:13
     * @Param [request, response]
     * @return java.lang.Object
     **/
    @RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CstBankVO vo = this.cmmCmmBindingCartService.selectById(Long.valueOf(id));
            if(null == vo){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
        }catch(BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch(Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /***
     *
     * @Description 修改客户开户行信息
     * @Author shijb
     * @Date 2018/7/10 11:52
     * @Param [request, response]
     * @return java.lang.Object
     **/
    @RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        CstBankVO entity = null;
        try {
            entity = new CstBankVO();
            entity = this.getRequestParamForVo(request);
            entity.setId(Long.valueOf(id));
            //TODO ADD PARAM
            boolean success = this.cmmCmmBindingCartService.modify(entity);
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    private CstBankVO getRequestParamForVo(HttpServletRequest request)throws BaseException{
        String accNm = request.getParameter("accNm");//开户名称
        String cardTel = request.getParameter("cardTel");//预留手机号
       // String accNo = request.getParameter("accNo");//银行账号
        String certNo = request.getParameter("certNo");//证件号
        String cstId = request.getParameter("cstId");//客户id(隐藏域)

        CstBankVO cstBankVO = new CstBankVO();
        if (StringUtils.isNotEmpty(accNm)) {
            cstBankVO.setAccNm(accNm.trim());
        }
        if (StringUtils.isNotEmpty(cardTel)) {
            cstBankVO.setCardTel(cardTel.trim());
        }
       /* if (StringUtils.isNotEmpty(accNo)) {
            cstBankVO.setAccNo(accNo.trim());
        }*/
        if (StringUtils.isNotEmpty(certNo)) {
            cstBankVO.setCertNo(certNo.trim());
        }
        if (StringUtils.isNotEmpty(cstId)) {
            cstBankVO.setCstId(Long.valueOf(cstId));
        }

        cstBankVO.setMdfTm(new Date());
        cstBankVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        return cstBankVO;
    }

    /**
     *
     * @Description 删除客户开户行信息，包括与其关联的签约银行数据
     * @Author shijb
     * @Date 2018/7/10 15:00
     * @Param [request, response]
     * @return cmm.mid.core.framework.page.DataResultVO
     **/
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        //String cstId = request.getParameter("cstId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeById", "删除数据失败.参数丢失[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            CstBankVO cstBankVO = new CstBankVO();
            cstBankVO.setId(Long.valueOf(id));
            cstBankVO.setIsDel(1);
            cstBankVO.setMdfTm(new Date());
            cstBankVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
            boolean success = this.cmmCmmBindingCartService.removeById(cstBankVO);
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeById", "删除数据成功.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     *
     * @Description 设置自动代扣，包括开启、取消
     * @Author shijb
     * @Date 2018/7/23 11:04
     * @Param [request, response]
     * @return cmm.mid.core.framework.page.DataResultVO
     **/
    @RequestMapping(value = "/autoChargeOperate.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO autoChargeOperate(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long staTime = System.currentTimeMillis();
        String id = request.getParameter("id");
        String cstId = request.getParameter("cstId");
        String isAuto = request.getParameter("isAuto");//1开启，0取消
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(cstId) || StringUtils.isEmpty(isAuto)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "autoChargeOperate", "设置自动代扣失败.参数丢失[id="+id+"&cstId="+cstId+"&isAuto="+isAuto+"]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            boolean success = this.cmmCmmBindingCartService.autoChargeOperate(id,cstId,isAuto,CurrentThreadContext.getCurrentUserId());
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
                BaseLogUtils.info(logger, "autoChargeOperate", "设置自动代扣失败.[id="+id+"&cstId="+cstId+"&isAuto="+isAuto+"]", CurrentThreadContext.getCurrentUserName());
            }else{
                BaseLogUtils.info(logger, "autoChargeOperate", "设置自动代扣成功.[id="+id+"&cstId="+cstId+"&isAuto="+isAuto+"]", CurrentThreadContext.getCurrentUserName());
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "autoChargeOperate", "设置自动代扣失败.[id="+id+"&cstId="+cstId+"&isAuto="+isAuto+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            BaseLogUtils.error(logger, "autoChargeOperate", "设置自动代扣失败.[id="+id+"&cstId="+cstId+"&isAuto="+isAuto+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        Long endTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "autoChargeOperate", "设置自动代扣操作完成.耗时:" + (endTime - staTime) + "毫秒");
        return result;
    }

    /**
     * @MethodName sendSMS
     * @Description: TODO 银行卡信息补全选发短信
     * @Author: shijibin@lionbridgecapital.cn
     * @CreateDate: 2019/2/26 16:27
     * @Version: 1.0.0
     * @Param request
     * @Param response
     * @Return cmm.mid.core.framework.page.DataResultVO
     * @UpdateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
     */

    @RequestMapping(value = "/sendSMS.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO sendSMS(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long staTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "sendSMS", "银行卡信息补全选发短信.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);

        String paramList = request.getParameter("data");
        if(StringUtils.isEmpty(paramList)){
            BaseLogUtils.info(logger, "sendSMS", "请选择银行卡");
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请选择银行卡");
            return result;
        }

        JSONArray paramJsonList = JSONArray.parseArray(paramList);
        if(paramJsonList.size()==0){
            BaseLogUtils.info(logger, "sendSMS", "请选择银行卡");
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请选择银行卡");
            return result;
        }

        try {
            boolean success = this.cmmCmmBindingCartService.sendSMS(paramJsonList);
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
                BaseLogUtils.info(logger, "sendSMS", "银行卡信息补全选发短信失败.", CurrentThreadContext.getCurrentUserName());
            }else{
                BaseLogUtils.info(logger, "sendSMS", "银行卡信息补全选发短信成功.", CurrentThreadContext.getCurrentUserName());
            }

        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "sendSMS", "银行卡信息补全选发短信失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            BaseLogUtils.error(logger, "sendSMS", "银行卡信息补全选发短信失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        Long endTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "sendSMS", "银行卡信息补全选发短信操作完成.耗时:" + (endTime - staTime) + "毫秒");
        return result;
    }

    /**
     * @MethodName batchSendSMS
     * @Description: TODO 群发短信（查找所有四要素不全的银行卡客户批量发送）
     * @Author: shijibin@lionbridgecapital.cn
     * @CreateDate: 2019/2/26 16:28
     * @Version: 1.0.0
     * @Param request
     * @Param response
     * @Return cmm.mid.core.framework.page.DataResultVO
     * @UpdateRemark [序号][YYYY-MM-DD] [更改人姓名][变更描述]
     */

    @RequestMapping(value = "/batchSendSMS.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO batchSendSMS(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        Long staTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "batchSendSMS", "银行卡信息补全群发短信.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);

        try {
            boolean success = this.cmmCmmBindingCartService.batchSendSMS();
            if(!success){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
                BaseLogUtils.info(logger, "batchSendSMS", "银行卡信息补全群发短信失败.", CurrentThreadContext.getCurrentUserName());
            }else{
                BaseLogUtils.info(logger, "batchSendSMS", "银行卡信息补全群发短信成功.", CurrentThreadContext.getCurrentUserName());
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "batchSendSMS", "银行卡信息补全群发短信失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
            BaseLogUtils.error(logger, "batchSendSMS", "银行卡信息补全群发短信失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        Long endTime = System.currentTimeMillis();
        BaseLogUtils.info(logger, "batchSendSMS", "银行卡信息补全群发短信操作完成.耗时:" + (endTime - staTime) + "毫秒");
        return result;
    }

}
